package li.rafa.UrlShortener.client;

import li.rafa.UrlShortener.shared.ShortUrl;

import com.google.gwt.core.client.GWT;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

import static li.rafa.UrlShortener.client.UrlShortener.urlService;

public class Main extends Composite {

	private static MainUiBinder uiBinder = GWT.create(MainUiBinder.class);

	interface MainUiBinder extends UiBinder<Widget, Main> {
	}

	@UiField
	TextBox urlBox;

	@UiField
	TextBox keyWordBox;

	@UiField
	VerticalPanel resultContainer;

	public Main() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiHandler("urlBox")
	void onKeyUp(KeyUpEvent event) {
		if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			rpc();
		}
	}

	@UiHandler("keyWordBox")
	void onKeywordKeyUp(KeyUpEvent event) {
		if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			rpc();
		}
	}

	private void rpc() {
		if (urlBox.getText() != null && urlBox.getText().trim().length() > 0 || keyWordBox.getText() != null && keyWordBox.getText().trim().length() > 0) {
			urlService.getShortenedUrl(urlBox.getText(), keyWordBox.getText(), new AsyncCallback<ShortUrl>() {
				public void onSuccess(ShortUrl result) {
					resultContainer.clear();
					resultContainer.add(new Label(Window.Location.getProtocol()+"//"+Window.Location.getHost() + "/" + result.getCode()));
					resultContainer.add(new Label(result.getOrginalUrl()));
				}

				public void onFailure(Throwable caught) {
					resultContainer.add(new Label(caught.toString()));
				}
			});
		}
	}

}
